package com.csun.cmny.provider.service.impl;

import com.csun.cmny.base.dto.LoginAuthDto;
import com.csun.cmny.base.enums.ErrorCodeEnum;
import com.csun.cmny.core.support.BaseService;
import com.csun.cmny.provider.dao.DmcCsunCameraUnalertAreaPlanMapper;
import com.csun.cmny.provider.device.csun.camera.CameraMessageHandler;
import com.csun.cmny.provider.exceptions.DmcBizException;
import com.csun.cmny.provider.model.constant.CameraConstant;
import com.csun.cmny.provider.model.constant.DeviceConstant;
import com.csun.cmny.provider.model.domain.DmcCsunCameraUnalertAreaPlan;
import com.csun.cmny.provider.model.domain.DmcDevice;
import com.csun.cmny.provider.model.dto.camera.UnalertAeraPlanDto;
import com.csun.cmny.provider.model.entity.CoordinateEntity;
import com.csun.cmny.provider.model.vo.csuncamera.UnalertAeraPlanVO;
import com.csun.cmny.provider.service.DmcCsunCameraUnalertAreaPlanService;
import com.csun.cmny.provider.service.DmcDeviceService;
import com.google.common.collect.Lists;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONArray;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import tk.mybatis.mapper.entity.Example;

import javax.annotation.Resource;

import java.util.List;

@Service
@Transactional(rollbackFor = Exception.class)
@Slf4j
public class DmcCsunCameraUnalertAreaPlanServiceImpl extends BaseService<DmcCsunCameraUnalertAreaPlan>
        implements DmcCsunCameraUnalertAreaPlanService {
    @Resource
    private DmcCsunCameraUnalertAreaPlanMapper dmcCsunCameraUnalertAreaPlanMapper;
    @Resource
    private DmcDeviceService dmcDeviceService;
    @Resource
    private CameraMessageHandler cameraMessageHandler;

    @Override
    public int savePlan(UnalertAeraPlanDto dto, LoginAuthDto loginAuthDto) {

        DmcCsunCameraUnalertAreaPlan plan = new DmcCsunCameraUnalertAreaPlan();
        BeanUtils.copyProperties(dto, plan);
        plan.setCoordinateList(JSONArray.fromObject(dto.getList()).toString());

        //检验坐标个数
        List<CoordinateEntity> coordinateEntityList = dto.getList();
        if (coordinateEntityList.size() > CameraConstant.MAX_COORDINATE_NUMBER || coordinateEntityList.size() < CameraConstant.MIN_COORDINATE_NUMBER) {
            throw new DmcBizException(ErrorCodeEnum.DMC100616006);
        }
        //同名校验
        if (checkPlanNameExsit(plan)) {
            throw new DmcBizException(ErrorCodeEnum.DMC100616004);
        }

        int ret = 0;

        plan.setStatus(CameraConstant.UN_USERD_PLAN);
        if (plan.isNew()) {
            //方案个数校验
            if (checkPlanNumber(plan)) {
                throw new DmcBizException(ErrorCodeEnum.DMC100616005);
            }
            plan.setUpdateInfo(loginAuthDto);
            ret = dmcCsunCameraUnalertAreaPlanMapper.insertSelective(plan);
        } else {
            ret = dmcCsunCameraUnalertAreaPlanMapper.updateByPrimaryKeySelective(plan);
        }

        return plan.getId().intValue();
    }

    public int choosePlanToCamera(Long planId) {

        //校验坐标与库中是否一致
        DmcCsunCameraUnalertAreaPlan plan = selectByKey(planId);

        DmcDevice dmcDevice = dmcDeviceService.selectByKey(plan.getDeviceId());
        if (dmcDevice.getDeviceType() != DeviceConstant.CSUN_CAMERA) {
            throw new DmcBizException(ErrorCodeEnum.DMC10068001, dmcDevice.getId());
        }

        //将其他计划置为未使用
        DmcCsunCameraUnalertAreaPlan planCheck = new DmcCsunCameraUnalertAreaPlan();
        planCheck.setDeviceId(dmcDevice.getId());
        List<DmcCsunCameraUnalertAreaPlan> planList = select(planCheck);
        for(DmcCsunCameraUnalertAreaPlan p : planList){
            if(!p.getId().equals(planId) || p.getStatus().equals(CameraConstant.USING_PLAN)){
                p.setStatus(CameraConstant.UN_USERD_PLAN);
                dmcCsunCameraUnalertAreaPlanMapper.updateByPrimaryKeySelective(p);
            }
            if(p.getId().equals(planId)){
                p.setStatus(CameraConstant.USING_PLAN);
                dmcCsunCameraUnalertAreaPlanMapper.updateByPrimaryKeySelective(p);
            }
        }

        JSONArray list = JSONArray.fromObject(plan.getCoordinateList());
        //设备指令下发
        cameraMessageHandler.sendUnalertAreaMsg(plan.getDeviceId(),list,plan.getHeight(),plan.getWidth());

        return 1;
    }

    @Override
    public List<UnalertAeraPlanVO> listUnalertAeraPlan(Long deviceId) {
        DmcCsunCameraUnalertAreaPlan planQuery = new DmcCsunCameraUnalertAreaPlan();
        planQuery.setDeviceId(deviceId);
        List<DmcCsunCameraUnalertAreaPlan> dmcList = select(planQuery);
        List<UnalertAeraPlanVO> voList = Lists.newArrayList();

        if (dmcList.size() > 0) {
            dmcList.forEach(d -> {
                UnalertAeraPlanVO vo = new UnalertAeraPlanVO();
                JSONArray jsonArray = JSONArray.fromObject(d.getCoordinateList());
                vo.setList(jsonArray);
                vo.setHeight(d.getHeight());
                vo.setWidth(d.getWidth());
                BeanUtils.copyProperties(d, vo);
                voList.add(vo);
            });
        }
        return voList;
    }

    private boolean checkPlanNumber(DmcCsunCameraUnalertAreaPlan plan) {
        DmcCsunCameraUnalertAreaPlan planCheck = new DmcCsunCameraUnalertAreaPlan();
        planCheck.setDeviceId(plan.getDeviceId());
        int i = selectCount(planCheck);
        return i > CameraConstant.MAX_UNALERT_AREA_PLAN_NUMBER ? true : false;
    }

    private boolean checkPlanNameExsit(DmcCsunCameraUnalertAreaPlan plan) {
        Example example = new Example(DmcCsunCameraUnalertAreaPlan.class);
        Example.Criteria criteria = example.createCriteria();
        if (plan.getId() != null) {
            criteria.andNotEqualTo("id", plan.getId());
        }
        criteria.andEqualTo("planName", plan.getPlanName());
        criteria.andEqualTo("deviceId", plan.getDeviceId());
        int i = selectCountByExample(example);
        return i > 0 ? true : false;
    }
}
